<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="search-wrapper">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入角色名称" clearable />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="queryParams.code" placeholder="请输入角色编码" clearable />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card shadow="never" class="table-wrapper">
      <template #header>
        <div class="card-header">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>新增
          </el-button>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="roleList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column prop="name" label="角色名称" min-width="120" show-overflow-tooltip />
        <el-table-column prop="code" label="角色编码" min-width="120" show-overflow-tooltip />
        <el-table-column prop="description" label="描述" min-width="180" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80" align="center">
          <template #default="{ row }">
            <el-tag :type="row.status ? 'success' : 'danger'">
              {{ row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleUpdate(row)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="success" link @click="handlePermission(row)">
              <el-icon><Setting /></el-icon>权限设置
            </el-button>
            <el-button type="danger" link @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.page_size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="roleForm.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      title="权限设置"
      v-model="permDialogVisible"
      width="600px"
      append-to-body
      destroy-on-close
    >
      <el-form label-width="80px">
        <el-form-item label="角色名称">
          <span>{{ currentRole.name }}</span>
        </el-form-item>
        <el-form-item label="权限分配">
          <el-tree
            ref="permTreeRef"
            :data="permissionTree"
            show-checkbox
            node-key="id"
            :props="{ label: 'name', children: 'children' }"
            :default-checked-keys="checkedPermissionIds"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPermission">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, Setting } from '@element-plus/icons-vue'
import { useThemeStore } from '@/store/theme'
import { getRoles, getRole, createRole, updateRole, deleteRole } from '@/api/role'
import { getPermissionTree } from '@/api/permission'

// 查询参数
const queryParams = reactive({
  page: 1,
  page_size: 10,
  name: '',
  code: '',
  status: null
})

// 表格数据
const roleList = ref([])
const total = ref(0)
const loading = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // add 或 update
const dialogTitle = ref('添加角色')
const roleFormRef = ref(null)
const queryFormRef = ref(null)

// 角色表单
const roleForm = reactive({
  id: null,
  name: '',
  code: '',
  description: '',
  status: true
})

// 表单校验规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

// 权限设置相关
const permDialogVisible = ref(false)
const permTreeRef = ref(null)
const permissionTree = ref([])
const checkedPermissionIds = ref([])
const currentRole = ref({})

// 获取角色列表
const getRoleList = async () => {
  loading.value = true
  try {
    const res = await getRoles(queryParams)
    roleList.value = res.data
    total.value = res.page_info.total
  } catch (error) {
    console.error('获取角色列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取权限树形数据
const getPermissionTreeData = async () => {
  try {
    const res = await getPermissionTree()
    permissionTree.value = res.data
  } catch (error) {
    console.error('获取权限树形数据失败:', error)
  }
}

// 查询
const handleQuery = () => {
  queryParams.page = 1
  getRoleList()
}

// 重置查询
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  getRoleList()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  queryParams.page_size = size
  getRoleList()
}

// 添加角色
const handleAdd = () => {
  resetRoleForm()
  dialogType.value = 'add'
  dialogTitle.value = '添加角色'
  dialogVisible.value = true
}

// 编辑角色
const handleUpdate = async (row) => {
  resetRoleForm()
  dialogType.value = 'update'
  dialogTitle.value = '编辑角色'
  
  try {
    const res = await getRole(row.id)
    const roleData = res.data
    
    // 填充表单数据
    roleForm.id = roleData.id
    roleForm.name = roleData.name
    roleForm.code = roleData.code
    roleForm.description = roleData.description
    roleForm.status = roleData.status
    
    dialogVisible.value = true
  } catch (error) {
    console.error('获取角色详情失败:', error)
    ElMessage.error('获取角色详情失败')
  }
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除角色 ${row.name} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteRole(row.id)
      ElMessage.success('删除成功')
      getRoleList()
    } catch (error) {
      console.error('删除角色失败:', error)
      ElMessage.error('删除角色失败')
    }
  }).catch(() => {})
}

// 权限设置
const handlePermission = async (row) => {
  currentRole.value = row
  
  try {
    // 获取角色详情，包括权限信息
    const res = await getRole(row.id)
    const roleData = res.data
    
    // 设置已选中的权限ID
    checkedPermissionIds.value = roleData.permissions.map(item => item.id)
    
    // 打开权限设置对话框
    permDialogVisible.value = true
  } catch (error) {
    console.error('获取角色权限失败:', error)
    ElMessage.error('获取角色权限失败')
  }
}

// 提交权限设置
const submitPermission = async () => {
  try {
    // 获取选中的权限ID
    const checkedKeys = permTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permTreeRef.value.getHalfCheckedKeys()
    const permissionIds = [...checkedKeys, ...halfCheckedKeys]
    
    // 更新角色权限
    await updateRole(currentRole.value.id, {
      permission_ids: permissionIds
    })
    
    ElMessage.success('权限设置成功')
    permDialogVisible.value = false
    getRoleList()
  } catch (error) {
    console.error('权限设置失败:', error)
    ElMessage.error('权限设置失败')
  }
}

// 重置角色表单
const resetRoleForm = () => {
  roleForm.id = null
  roleForm.name = ''
  roleForm.code = ''
  roleForm.description = ''
  roleForm.status = true
  
  if (roleFormRef.value) {
    roleFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  roleFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          // 创建角色
          await createRole(roleForm)
          ElMessage.success('添加成功')
        } else {
          // 更新角色
          await updateRole(roleForm.id, roleForm)
          ElMessage.success('更新成功')
        }
        
        dialogVisible.value = false
        getRoleList()
      } catch (error) {
        console.error('保存角色失败:', error)
        ElMessage.error('保存角色失败')
      }
    }
  })
}

onMounted(() => {
  getRoleList()
  getPermissionTreeData()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 0;
  
  .search-wrapper {
    margin-bottom: 20px;
    border: 1px solid var(--border-color);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
    
    :deep(.el-card__body) {
      background-color: var(--card-bg-color);
      padding: 20px;
    }
    
    :deep(.el-form) {
      .el-form-item {
        margin-bottom: 16px;
        
        .el-form-item__label {
          color: var(--text-color);
          font-weight: 500;
        }
        
        .el-input__wrapper {
          border-radius: 6px;
          transition: all 0.3s ease;
          background-color: var(--card-bg-color);
          
          &:hover {
            border-color: var(--border-color);
          }
          
          &.is-focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
        }
        
        .el-select {
          .el-input__wrapper {
            border-radius: 6px;
            background-color: var(--card-bg-color);
          }
        }
        
        .el-button {
          border-radius: 6px;
          font-weight: 500;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }
  }
  
  .table-wrapper {
    border: 1px solid var(--border-color);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
    
    :deep(.el-card__header) {
      background-color: var(--header-bg-color);
      border-bottom: 1px solid var(--border-color);
      
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .el-button {
          border-radius: 6px;
          font-weight: 500;
          transition: all 0.3s ease;
          
          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
          }
        }
      }
    }
    
    :deep(.el-card__body) {
      background-color: var(--card-bg-color);
      padding: 20px;
    }
    
    :deep(.el-table) {
      border-radius: 6px;
      overflow: hidden;
      background-color: var(--card-bg-color);
      
      .el-table__header {
        th {
          background-color: var(--header-bg-color);
          color: var(--text-color);
          font-weight: 600;
          border-bottom: 1px solid var(--border-color);
        }
      }
      
      .el-table__body {
        tr {
          background-color: var(--card-bg-color);
          
          &:hover > td {
            background-color: var(--hover-bg-color) !important;
          }
          
          td {
            border-bottom: 1px solid var(--border-color);
            color: var(--text-color);
            
            .el-tag {
              border-radius: 4px;
              font-weight: 500;
            }
            
            .el-button {
              border-radius: 4px;
              font-weight: 500;
              transition: all 0.3s ease;
              color: var(--text-color);
              
              &:hover {
                transform: translateY(-1px);
              }
            }
          }
        }
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    
    :deep(.el-pagination) {
      .el-pager li {
        border-radius: 4px;
        margin: 0 2px;
        transition: all 0.3s ease;
        background-color: var(--card-bg-color);
        color: var(--text-color);
        
        &:hover {
          background-color: var(--hover-bg-color);
        }
        
        &.is-active {
          background-color: #409eff;
          color: #ffffff;
        }
      }
      
      .btn-prev,
      .btn-next {
        border-radius: 4px;
        transition: all 0.3s ease;
        background-color: var(--card-bg-color);
        color: var(--text-color);
        
        &:hover {
          background-color: var(--hover-bg-color);
        }
      }
    }
  }
}

// 对话框样式优化
:deep(.el-dialog) {
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  background-color: var(--card-bg-color);
  
  .el-dialog__header {
    background-color: var(--header-bg-color);
    border-bottom: 1px solid var(--border-color);
    border-radius: 8px 8px 0 0;
    
    .el-dialog__title {
      color: var(--text-color);
      font-weight: 600;
    }
  }
  
  .el-dialog__body {
    background-color: var(--card-bg-color);
    padding: 24px;
    color: var(--text-color);
    
    .el-form {
      .el-form-item {
        margin-bottom: 20px;
        
        .el-form-item__label {
          color: var(--text-color);
          font-weight: 500;
        }
        
        .el-input__wrapper,
        .el-textarea__inner {
          border-radius: 6px;
          transition: all 0.3s ease;
          background-color: var(--card-bg-color);
          
          &:hover {
            border-color: var(--border-color);
          }
          
          &:focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
        }
        
        .el-radio-group {
          .el-radio {
            margin-right: 20px;
            
            .el-radio__label {
              color: var(--text-color);
            }
          }
        }
      }
    }
    
    // 权限树样式
    .el-tree {
      border: 1px solid var(--border-color);
      border-radius: 6px;
      padding: 10px;
      background-color: var(--card-bg-color);
      
      .el-tree-node {
        .el-tree-node__content {
          border-radius: 4px;
          transition: all 0.3s ease;
          
          &:hover {
            background-color: var(--hover-bg-color);
          }
        }
        
        .el-tree-node__label {
          color: var(--text-color);
          font-weight: 500;
        }
      }
    }
  }
  
  .el-dialog__footer {
    background-color: var(--header-bg-color);
    border-top: 1px solid var(--border-color);
    border-radius: 0 0 8px 8px;
    
    .dialog-footer {
      .el-button {
        border-radius: 6px;
        font-weight: 500;
        transition: all 0.3s ease;
        
        &:hover {
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }
      }
    }
  }
}
</style>
